package com.itqf.Controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.itqf.Enum.CodeEnum;
import com.itqf.Service.User.UserCenter;
import com.itqf.Util.AliAccessKey;
import com.itqf.Util.DTO.ResultDTO;
import com.itqf.Util.UpLoadUtil;
import com.itqf.Util.YzmUtil;
import com.itqf.Util.requestHeader.RequestHeaderUtil;
import com.itqf.entity.Manager;
import com.itqf.entity.User;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.FileInputStream;


/*
* @Author 李鹏鹏
* @Description //TODO
* @Date
* @Param
* @return
**/
@Controller
@RequestMapping("/huileme/a/u/userManagementController")
public class userManagementController {

    @Resource
    private UserCenter userCenter;
    /**
     * 账户中心根据userToken码查询user信息反馈页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/accountu",method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO<User> getUser( HttpServletRequest request){
        //调用获取请求头中的工具类
        RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
        final User getheader = requestHeaderUtil.getheader(request);
        final String userid1 = getheader.getUserid();
        //使用userToken查询user信息
        User massage = userCenter.findbytoken(userid1);
        ResultDTO resultDTO=new ResultDTO();
        if (massage!=null) {
            resultDTO.setData(massage);
            resultDTO.setMessage(CodeEnum.selectsuccess.getMsg());
            resultDTO.setCode(CodeEnum.selectsuccess.getCode());
        }
        return resultDTO;
    }




    /**
     * 根据Token修改用户头像
     * @param headPortrait
     * @return
     */
    @PostMapping("/toupload")
    @ResponseBody
    public ResultDTO updateImage(MultipartFile headPortrait, HttpServletRequest request){
        //调用获取请求头中的工具类
        RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
        final User getheader = requestHeaderUtil.getheader(request);
        final String userid1 = getheader.getUserid();
        ResultDTO resultDTO=new ResultDTO();
        if(headPortrait==null){
            resultDTO.setMessage(CodeEnum.selecterror.getMsg());
            resultDTO.setCode(CodeEnum.selecterror.getCode());
        }
        //将文件上传到upload目录下
        String originalFilename = UpLoadUtil.getup(headPortrait, request);

        int i = userCenter.updateIconByToken(originalFilename, userid1);

        if (i<0){
            //头像更换失败返回错误状态码200
            resultDTO.setMessage(CodeEnum.updateImgErro.getMsg());
            resultDTO.setCode(CodeEnum.updateImgErro.getCode());
            return resultDTO;
        }else
        {
            resultDTO.setMessage(CodeEnum.updateImgSuccess.getMsg());
            resultDTO.setCode(CodeEnum.updateImgSuccess.getCode());

        }
        return resultDTO;
    }

    @RequestMapping("/down")
    public String  down(String userToken,HttpServletRequest request, HttpServletResponse response,ModelMap map) throws Exception{

        User user = userCenter.findbytoken("2222");
        String userimg = user.getUserimg();
        /*IOUtils.copy(new FileInputStream(userimg), response.getOutputStream());*/
        map.addAttribute("img", userimg);
        return "image";

    }

    /** @Description: 发送短信验证码，并把生成的验证码保存到session中
     * @Param:
     * @return:
     * @Author: 李鹏鹏
     * @Date: 上午 10:37
     */
    @PostMapping("/getYzm")
    @ResponseBody
    public Manager getMass(String userPhone,HttpServletRequest request1) throws ClientException {
        Manager m=new Manager();
        HttpSession session = request1.getSession();
        //获取随机生成的验证码
        Integer yzm = YzmUtil.getYzm();
        session.setAttribute("YZM", yzm);
        //以短信方式发送验证码
        //1、调用阿里通信接口
        System.setProperty("sun.net.client.defaultConnectTimeout",
                "1000");
        System.setProperty("sun.net.client.defaultReadTimeout",
                "1000");
//初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品
        //名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品
        //域名（接口地址固定，无需修改）
//替换成你的AK
        final String accessKeyId = AliAccessKey.accessKeyId;//你的
        //accessKeyId,参考本文档步骤2
        final String accessKeySecret =
                AliAccessKey.accessKeySecret;//你的accessKeySecret，参考本文档步骤2
//初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId,
                accessKeySecret);
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai",
                product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
        SendSmsRequest request = new SendSmsRequest();
//使用post提交
        request.setMethod(MethodType.POST);
//必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上
        // 限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信
        // 推荐使用单条调用的方式
        request.setPhoneNumbers(userPhone);
//必填:短信签名-可在短信控制台中找到
        request.setSignName("会了么");
//必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_175532623");
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的
        // 验证码为${code}"时,此处的值为
//友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行
        // 符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致
        //JSON在服务端解析失败
//生成几位的验证码
        request.setTemplateParam("{code:"+yzm+"}");
//可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用
        //户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值
        //带回给调用者
        request.setOutId("qf");
//请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse =
                acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode()==null&&!sendSmsResponse.getCode().equals("OK")){
            //短信验证码发送失败时返回
            m.setCorrectMessages("短信验证码发送失败！");
            return m;
        }

        m.setCorrectMessages("短信验证码发送成功！");
        System.out.println(yzm);
        //设置session有效期为60秒内有效
        //session.setMaxInactiveInterval(1*60);

        //把验证码保存到Session中

        return m;
    }



    /**
     * 更换手机号
     * @param userPhone
     * @param request
     * @param verificationCode
     * @return
     */
    @PutMapping("/updatePhone")
    @ResponseBody
    public ResultDTO updatePhone(String userPhone, String verificationCode,HttpServletRequest request){
        //调用获取请求头中的工具类
        RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
        final User getheader = requestHeaderUtil.getheader(request);
        final String userid1 = getheader.getUserid();
        HttpSession session = request.getSession();
        //从session里面取出保存的验证码
        Object yzm = session.getAttribute("YZM");
        ResultDTO resultDTO=new ResultDTO();
        //验证验证码是否正确
        if(!yzm.equals(verificationCode)){
            //验证码错误时返回
            resultDTO.setCode(CodeEnum.selectsuccess.getCode());
            resultDTO.setMessage("验证码错误");
        }
        //验证码正确则调用修改手机号方法
        int updatePhoneByToken = userCenter.updatePhoneByToken(userPhone, userid1);
        if (updatePhoneByToken==0){
            //更换失败返回
            resultDTO.setCode(CodeEnum.Updateerror.getCode());
            resultDTO.setMessage(CodeEnum.Updateerror.getMsg());
        }else
        {
            resultDTO.setCode(CodeEnum.Updatesuccess.getCode());
            resultDTO.setMessage(CodeEnum.Updatesuccess.getMsg());
        }
        return resultDTO;
    }


    /**
     * 根据token修改用户昵称
     * @param userNickName
     * @param request
     * @return
     */

    @PostMapping("/userNickName")
    @ResponseBody
    public ResultDTO updateName(String userNickName,HttpServletRequest request){
        //调用获取请求头中的工具类
        RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
        final User getheader = requestHeaderUtil.getheader(request);
        final String userid1 = getheader.getUserid();
        //根据用户Toke修改用户昵称
        int massage=userCenter.updateName(userNickName,userid1);
        ResultDTO resultDTO=new ResultDTO();
        if (massage!=1){
            //更换失败返回
            resultDTO.setCode(CodeEnum.Updatesuccess.getCode());
            resultDTO.setMessage(CodeEnum.Updatesuccess.getMsg());
        }else
        {
            resultDTO.setCode(CodeEnum.Updatesuccess.getCode());
            resultDTO.setMessage(CodeEnum.Updatesuccess.getMsg());
        }

        return resultDTO;
    }




}
